package com.tzpay.tzpay.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.pullloadmorerecyclerview.PullLoadMoreRecyclerView;
import com.tzpay.tzpay.R;
import com.tzpay.tzpay.adapter.SwpipeRecycleViewOnScrollListener;
import com.tzpay.tzpay.adapter.TradeListAdapter;
import com.tzpay.tzpay.bean.OrderInfo;
import com.tzpay.tzpay.bean.UserInfo;
import com.tzpay.tzpay.common.StaticVars;
import com.tzpay.tzpay.presenter.BaseLogicView;
import com.tzpay.tzpay.presenter.TradeListPresenter;
import com.tzpay.tzpay.ui.BaseFragment;
import com.tzpay.tzpay.ui.activity.TradeListActivity;
import com.tzpay.tzpay.utils.SnackBarUtils;
import com.tzpay.tzpay.utils.T;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/3/13 0013.
 */
public class TradeListFragment extends BaseFragment implements BaseLogicView {
    private static final String TAG = "TradeListFragment";

    public static TradeListFragment instance() {
        TradeListFragment fragment = new TradeListFragment();
        return fragment;
    }

    @Bind(R.id.id_recyclerview)
    PullLoadMoreRecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.tv_nodata)
    TextView tvNodata;

    private static final int LIMIT = 20;
    private static final int FIRST_PAGE = 1;
    private static final String SORT_ORDER = StaticVars.Column._ID + " DESC LIMIT " + LIMIT;

    private TradeListAdapter adapter;
    private ArrayList<OrderInfo> infos = new ArrayList<>();
    private int currPage = 1;
    private TradeListPresenter presenter;
    private boolean noMoreData = false;
    private boolean isLoading = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tradelist, null);
        ButterKnife.bind(this, view);
        presenter = new TradeListPresenter(this);
        initSwipeLayout();
        initRecycleView();
        loadData();
        return view;
    }

    private void initRecycleView() {
        adapter = new TradeListAdapter(getActivity(), infos);
        recyclerView.setLinearLayout();
        recyclerView.setAdapter(adapter);
        recyclerView.setPullRefreshEnable(false);
        recyclerView.setOnPullLoadMoreListener(new PullLoadMoreListener());
        recyclerView.addOnScrollListener(new SwpipeRecycleViewOnScrollListener(refreshLayout));
    }

    private void initSwipeLayout() {
        refreshLayout.setColorSchemeResources(R.color.primary, R.color.primary, R.color.primary);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }

    @OnClick(R.id.tv_nodata)
    public void onNoDataClick() {
        loadData();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (TradeListActivity.isNeadRefresh) {
            TradeListActivity.isNeadRefresh = false;
            refresh();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        TradeListActivity.isNeadRefresh = true;
        presenter.onDestory();
    }

    private void loadData() {
        if (isLoading) {
            return;
        }
        if (noMoreData) {
            loadingCompleted();
            SnackBarUtils.showLongSnackBar(refreshLayout, getString(R.string.no_more_data));
            return;
        }
        isLoading = true;
        if (currPage == FIRST_PAGE) {
            presenter.getOrderInfos(StaticVars.Column.ORDER_NO + " != ? AND "
                            + StaticVars.Column.MERCHAT_ID + " = ? ",
                    new String[]{"", UserInfo.getInstance().getMerchantNo()}, SORT_ORDER);
        } else {
            int size = infos.size();
            if (size >= 1) {
                OrderInfo lastInfo = infos.get(infos.size() - 1);
                presenter.getOrderInfos(StaticVars.Column.ORDER_NO + " != ? AND "
                                + StaticVars.Column.MERCHAT_ID + " = ? AND "
                                + StaticVars.Column._ID + " < ? ",
                        new String[]{"", UserInfo.getInstance().getMerchantNo(), String.valueOf(lastInfo.get_id())},
                        SORT_ORDER);
            }
        }
    }

    private void refresh() {
        noMoreData = false;
        currPage = FIRST_PAGE;
        adapter.clearData();
        loadData();
    }

    @Override
    public void showProgress() {
        T.e(TAG, "showProgress()");
//        refreshLayout.setRefreshing(true);

        refreshLayout.post(new Runnable() {

            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
    }

    @Override
    public void onFailed(String resperr) {
        T.e(TAG, "onFailed  resperr = " + resperr);
        tvNodata.setText(resperr);
        SnackBarUtils.showLongSnackBar(refreshLayout, resperr);
        loadingCompleted();
    }

    @Override
    public void onSuccess(Object result) {
        loadingCompleted();
        if (result == null) {
            if (currPage == 1) {
                tvNodata.setText(getString(R.string.text_no_data));
                tvNodata.setVisibility(View.VISIBLE);
            } else {
                SnackBarUtils.showLongSnackBar(refreshLayout, getString(R.string.no_more_data));
            }
            return;
        }
        ArrayList<OrderInfo> infos = (ArrayList<OrderInfo>) result;
        if (currPage == 1 && infos.size() == 0) {
            // 第一次加载没有数据
//            recyclerView.setVisibility(View.GONE);
            tvNodata.setText(getString(R.string.text_no_data));
            tvNodata.setVisibility(View.VISIBLE);
            return;
        }
        recyclerView.setVisibility(View.VISIBLE);
        tvNodata.setVisibility(View.GONE);
        if (infos.size() < LIMIT) {
            // 无更多数据
            noMoreData = true;
        }
        adapter.addData(infos);
        currPage++;
    }

    class PullLoadMoreListener implements PullLoadMoreRecyclerView.PullLoadMoreListener {
        @Override
        public void onRefresh() {
        }

        @Override
        public void onLoadMore() {
            loadData();
        }
    }

    private void loadingCompleted() {
        recyclerView.setPullLoadMoreCompleted();
        refreshLayout.setRefreshing(false);
        isLoading = false;
    }
}
